package com.zys.background.auth.handler;

import com.zys.background.common.constant.SecurityConstants;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zys
 * @since 2022-11-21
 */
@RequiredArgsConstructor
@SuppressWarnings("AlibabaClassNamingShouldBeCamel")
public class OAuth2LogoutHandler implements LogoutHandler {
  private final OAuth2AuthorizationService authorizationService;

  @Override
  public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    String authHeader = request.getHeader(SecurityConstants.AUTHORIZATION);
    if(!StringUtils.hasText(authHeader)){
      return;
    }
    String token = authHeader.replaceAll(SecurityConstants.TOKEN_PREFIX + " *", "");
    OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
    if(authorization == null){
      return;
    }

    OAuth2Authorization.Token<OAuth2AccessToken> accessToken = authorization.getAccessToken();
    if(accessToken == null || !StringUtils.hasText(accessToken.getToken().getTokenValue())){
      return;
    }

    authorizationService.remove(authorization);
  }
}
